﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace a20_ControlGallery
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void HandleSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender == null)
                return;

            Details.DataContext = (sender as ListBox).DataContext;
            parseCurrentCode();
        }

        private void LoadClick(object sender, RoutedEventArgs e)
        {
            parseCurrentCode();
        }

        private void parseCurrentCode()
        {

            var str = TextBox1.Text;
            if (String.IsNullOrEmpty(str))
                return;

            try
            {
                var ms = new MemoryStream();
                var sw = new StreamWriter(ms);
                sw.Write(str);
                sw.Flush();
                ms.Flush();
                ms.Position = 0;
                try
                {
                    var content = XamlReader.Load(ms);
                    if (content != null)
                    {
                        PreviewGrid.Children.Clear();
                        PreviewGrid.Children.Add((UIElement)content);
                    }
                    //TextBox1.Foreground = Brushes.Black;
                    ErrorText.Text = "";
                }

                catch (XamlParseException xpe)
                {
                    //TextBox1.Foreground = Brushes.Red;
                    //TextBox1.TextWrapping = TextWrapping.Wrap;
                    ErrorText.Text = xpe.Message;
                }
            }
            catch (Exception)
            {
                // ignored
            }

        }
    }
}
